package org.example;

import instrument.DBUtil;
import instrument.JdbcUtil;
import instrument.LogUtil;
import instrument.MD5Util;

import java.util.*;
import java.text.SimpleDateFormat;

public class AdminService {
    private final List<User> users = new ArrayList<>();
    private User current;
    private final Scanner sc = new Scanner(System.in);
    private final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public AdminService() {
        DBUtil.initDB();
        users.addAll(JdbcUtil.loadUsers());
        // 初始化管理员账户
        if (users.stream().noneMatch(u -> u.getUsername().equals("admin"))) {
            users.add(new User(10001, "admin", MD5Util.encrypt("ynuinfo#777"),
                    "管理员", "13800000000", new Date(), false));
            JdbcUtil.saveUsers(users);
        }
    }

    public boolean login(String user, String pwd) {
        String enc = MD5Util.encrypt(pwd);
        current = users.stream()
                .filter(u -> u.getUsername().equals(user) && u.getPassword().equals(enc) && u.getUserType().equals("管理员"))
                .findFirst().orElse(null);
        if (current != null && current.isNeedChangePassword()) {
            System.out.println("请先修改初始密码！");
            changePasswordSelf();
        }
        return current != null;
    }

    public void menu() {
        while (true) {
            System.out.println("\n=== 管理员菜单 ===");
            System.out.println("1.修改自身密码 2.重置他人密码 3.用户管理 4.退出");
            switch (sc.nextLine().trim()) {
                case "1" -> changePasswordSelf();
                case "2" -> resetOthersPwd();
                case "3" -> userManage();
                case "4" -> {
                    JdbcUtil.saveUsers(users);
                    LogUtil.log(current.getUsername(), "退出登录");
                    return;
                }
                default -> System.out.println("无效选择");
            }
        }
    }

    private void changePasswordSelf() {
        System.out.print("输入新密码: ");
        String newPwd = sc.nextLine();
        current.setPassword(MD5Util.encrypt(newPwd));
        current.setNeedChangePassword(false);
        JdbcUtil.saveUsers(users);
        LogUtil.log(current.getUsername(), "修改管理员密码");
        System.out.println("修改成功");
    }

    private void resetOthersPwd() {
        System.out.print("输入要重置的用户名(经理/前台): ");
        String name = sc.nextLine();
        User u = users.stream().filter(x -> x.getUsername().equals(name)).findFirst().orElse(null);
        if (u == null || u.getUserType().equals("管理员")) {
            System.out.println("无法重置");
            return;
        }
        u.setPassword(MD5Util.encrypt("123456"));
        u.setNeedChangePassword(true);
        JdbcUtil.saveUsers(users);
        LogUtil.log(current.getUsername(), "重置" + u.getUserType() + name + "密码");
        System.out.println("已重置为123456");
    }

    private void userManage() {
        while (true) {
            System.out.println("\n1.列出全部 2.查询 3.增加 4.修改 5.删除 6.返回");
            switch (sc.nextLine().trim()) {
                case "1" -> users.stream()
                        .filter(u -> !u.getUserType().equals("管理员"))
                        .forEach(User::display);
                case "2" -> {
                    System.out.print("用户名或ID: ");
                    String key = sc.nextLine();
                    users.stream()
                            .filter(u -> !u.getUserType().equals("管理员"))
                            .filter(u -> u.getUsername().equals(key) || String.valueOf(u.getId()).equals(key))
                            .forEach(User::display);
                }
                case "3" -> addUser();
                case "4" -> modifyUser();
                case "5" -> delUser();
                case "6" -> {
                    return;
                }
            }
        }
    }

    private void addUser() {
        try {
            System.out.print("ID: ");
            int id = Integer.parseInt(sc.nextLine());
            if (users.stream().anyMatch(u -> u.getId() == id)) {
                System.out.println("ID已存在");
                return;
            }
            System.out.print("用户名: ");
            String name = sc.nextLine();
            if (users.stream().anyMatch(u -> u.getUsername().equals(name))) {
                System.out.println("用户名已存在");
                return;
            }
            System.out.print("电话: ");
            String tel = sc.nextLine();
            if (users.stream().anyMatch(u -> u.getTelephone().equals(tel))) {
                System.out.println("电话已存在");
                return;
            }
            System.out.print("类型(经理/前台): ");
            String type = sc.nextLine();
            if (!type.equals("经理") && !type.equals("前台")) {
                System.out.println("只能经理/前台");
                return;
            }
            users.add(new User(id, name, MD5Util.encrypt("123456"), type, tel, new Date(), true));
            JdbcUtil.saveUsers(users);
            LogUtil.log(current.getUsername(), "增加" + type + name);
            System.out.println("增加成功");
        } catch (Exception e) {
            System.out.println("输入错误");
        }
    }

    private void modifyUser() {
        System.out.print("输入要修改的用户名: ");
        String name = sc.nextLine();
        User u = users.stream()
                .filter(x -> x.getUsername().equals(name) && !x.getUserType().equals("管理员"))
                .findFirst().orElse(null);
        if (u == null) {
            System.out.println("未找到");
            return;
        }
        System.out.print("新类型(经理/前台): ");
        String type = sc.nextLine();
        if (!type.equals("经理") && !type.equals("前台")) {
            System.out.println("只能经理/前台");
            return;
        }
        System.out.print("新电话: ");
        String tel = sc.nextLine();
        u.setTelephone(tel);
        u.setUserType(type);
        JdbcUtil.saveUsers(users);
        LogUtil.log(current.getUsername(), "修改" + name + "信息");
        System.out.println("修改成功");
    }

    private void delUser() {
        System.out.print("输入要删除的用户名: ");
        String name = sc.nextLine();
        if (name.equals("admin")) {
            System.out.println("不能删除admin");
            return;
        }
        User u = users.stream().filter(x -> x.getUsername().equals(name)).findFirst().orElse(null);
        if (u == null || u.getUserType().equals("管理员")) {
            System.out.println("用户不存在或不能删除");
            return;
        }
        System.out.print("确认删除(y/n)? ");
        if (!sc.nextLine().trim().equalsIgnoreCase("y")) return;
        users.remove(u);
        JdbcUtil.saveUsers(users);
        LogUtil.log(current.getUsername(), "删除" + u.getUserType() + name);
        System.out.println("删除成功");
    }

    public List<User> getUsers() {
        return users;
    }
}